var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var fileStore = require('session-file-store')(session);
var logger = require('morgan');
let bodyParser=require('body-parser');
var fs = require('fs');

var app = express();

app.use(logger('dev'));
// app.use(express.json());
// app.use(express.urlencoded({ extended: false }));

app.use(bodyParser.urlencoded({
    parameterLimit: 100000,
    limit: '50mb',
    extended: true
}));
app.use(bodyParser.json({limit: '50mb', type: 'application/json'}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


//deploy client
app.use('/node_modules',express.static('../kobootstrapmobile/node_modules'));
app.use('/trainExam',express.static('../kobootstrapmobile/src'));

// 读取配置文件
{
    let files = fs.readdirSync('./configs/');
    files.forEach((val) => {
        let config = require('./configs/' + val);
        for (let key in config) {
            global[key] = config[key];
        }
    });
}

// 加载数据库
var db = require('./components/db');
app.db = db;

// 设置session
if (global.openRedis) {
    app.use(session({
        name: global.cookie.name,
        secret: global.session.secret,
        store : new RedisStore(global.redis),
        rolling:true,
        resave: global.session.resave,
        saveUninitialized: global.session.saveUninitialized,
        cookie : global.cookie
    }));
}
else {
    app.use(session({
        name: global.cookie.name,
        secret: global.session.secret,
        store: new fileStore(),
        resave: global.session.resave,
        saveUninitialized: global.session.saveUninitialized,
        cookie: global.cookie
    }));
}



// 加载路由
{
    let files = fs.readdirSync('./routers/common/');
    files.forEach((val) => {
        let router = require('./routers/common/' + val);
        app.use(global.contextPath + '/rest/' + val.split('.')[0], router);
    });
}




// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
